package pattern.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/*
 * @author changfei
 * @date  2023/11/28 14:46
 * @description
 */
public class CglibInterceptor implements MethodInterceptor {
    private Object target;

    private CglibInterceptor(Object target){
        this.target=target;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("方法执行前");
        Object invoke = methodProxy.invoke(target, objects);
        System.out.println("方法执行后");
        return invoke;
    }

    public Object getProxy(){
        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();

    }

    public static void main(String[] args) {
        CglibInterceptor cglibInterceptor = new CglibInterceptor(new CglibMe());
        CglibMe cglibMe = (CglibMe) cglibInterceptor.getProxy();
        cglibMe.work();
    }
}
